<template>
  <div class="app-container">
    <div class="search-box">
      <div class="form-box">
        <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" @submit.native.prevent>
          <el-form-item label="名称" prop="activityName">
            <el-input v-model="queryParams.activityName" placeholder="请输入名称" clearable :spellcheck="false"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-form>
      </div>
      <div class="btn-box">
        <div class="left-box">
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </div>
      </div>
    </div>
    <div class="handle-box">
      <el-button type="primary" icon="el-icon-plus" size="small" @click="showActivityEditDialog()">新增</el-button>
    </div>
    <div class="table-box">
      <el-table v-loading="loading" :data="tableData" height="100%">
        <el-table-column v-for="item in tableColumn" :key="item.prop" :label="item.label" :prop="item.prop"
          :class-name="item.className" :width="item.width" :min-width="item.minWidth" :sortable="item.sortable"
          :align="item.align || 'center'" :show-overflow-tooltip="item.showOverflowTooltip" :fixed="item.fixed"
          :resizable="false">
          <template slot-scope="{row}">
            <!-- 封面 -->
            <el-image v-if="item.prop == 'activityImage'" class="image" :src="row.activityImage"
              :preview-src-list="[row.activityImage]" alt="封面" />
            <!-- 操作 -->
            <span v-else-if="item.prop == 'handle'" class="handle">
              <el-link type="primary" @click="showActivityEditDialog(row)">修改</el-link>
              <el-link type="primary" @click="formDesign(row)">{{$route.meta.title}}设计</el-link>
              <el-link type="primary" @click="showActivityRecordDialog(row)">{{$route.meta.title}}记录</el-link>
            </span>
            <!-- 默认 -->
            <span v-else>{{ row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getData" />
    <!-- 弹窗动态组件 -->
    <component :is="dialogName" :visible.sync="dialogVisible" :params="dialogParams" :width="dialogWidth"
      :height="dialogHeight" @success="handleDialogSuccess" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import * as api from '@/api/activityManger/index.js';
import * as auth from '@/utils/auth.js';
// 批量局部注册组件
const componentsObj = {};
const req = require.context('./dialog', true, /\.vue$/);
req.keys().forEach((element, index) => {
  let name = element.replace(/(.*\/)|(\.vue)/gi, '');
  const config = req(element);
  componentsObj[name] = config.default || config;
});

export default {
  name: 'KHGL',
  components: componentsObj,
  data() {
    return {
      activityTypeId: null,
      loading: true, // 遮罩层
      total: 0, // 总条数
      tableColumn: [
        { label: '名称', prop: 'activityName', minWidth: 150 },
        { label: '封面', prop: 'activityImage', minWidth: 120 },
        { label: '开始时间', prop: 'startTime', minWidth: 100 },
        { label: '结束时间', prop: 'endTime', minWidth: 100 },
        { label: '描述', prop: 'description', minWidth: 500, showOverflowTooltip: true },
        { label: '操作', prop: 'handle', width: 85, fixed: 'right' },
      ],
      tableData: [], // 表格数据
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: '',
      },
      dialogName: null, // 弹窗组件名
      dialogVisible: false, // 弹窗显示
      dialogParams: null, // 弹窗参数
      dialogWidth: '', // 弹窗宽度
      dialogHeight: '', // 弹窗高度
    };
  },
  computed: {
    ...mapGetters(['name']),
  },
  created() {
    if (this.$route?.query?.activityTypeId) this.activityTypeId = this.$route.query.activityTypeId;
    this.queryParams.activityTypeId = this.activityTypeId;
  },
  mounted() {
    this.getData();
  },
  methods: {
    // 获取活动列表
    getData() {
      this.loading = true;
      api
        .getActivityList(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((err) => {
          if (err == '401') this.showLoginQiWeiDialog();
          console.log('err', err);
          this.loading = false;
        });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getData();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 修改/新增弹窗
    showActivityEditDialog(row) {
      this.dialogName = 'ActivityEditDialog';
      this.dialogVisible = true;
      this.dialogParams = { activityTypeId: this.activityTypeId, activityId: row?.id };
      this.dialogWidth = '500px';
      this.dialogHeight = 'auto';
    },
    // 记录弹窗
    showActivityRecordDialog(row) {
      this.dialogName = 'ActivityRecordDialog';
      this.dialogVisible = true;
      this.dialogParams = { activityTypeId: this.activityTypeId, activityId: row?.id };
      this.dialogWidth = '80%';
      this.dialogHeight = '80%';
    },
    // 表单设计弹窗
    formDesign(row) {
      api.getActivityOptionList({ activityId: row.id }).then(({ rows }) => {
        this.dialogName = 'FormDesignerDialog';
        this.dialogVisible = true;
        this.dialogParams = {
          activityId: row.id,
          optionId: rows[0]?.id,
          rule: rows[0] && JSON.parse(rows[0].rule),
          option: rows[0] && JSON.parse(rows[0].option),
          menuList: [
            {
              title: '投票选项',
              name: 'vote',
              list: [
                { label: '单选', name: 'radio', icon: 'icon-radio' },
                { label: '多选', name: 'checkbox', icon: 'icon-checkbox' },
              ],
            },
          ],
          config: {
            fieldReadonly: true,
            updateDefaultRule: {
              radio: {
                title: '张三',
                options: [
                  { label: '同意', value: '同意' },
                  { label: '不同意', value: '不同意' },
                  { label: '弃权', value: '弃权' },
                ],
              },
              checkbox: {
                title: '张三',
                options: [
                  { label: '同意', value: '同意' },
                  { label: '不同意', value: '不同意' },
                  { label: '弃权', value: '弃权' },
                ],
              },
            },
          },
        };
        this.dialogWidth = '90%';
        this.dialogHeight = '90%';
      });
    },
    // 处理弹窗success事件
    handleDialogSuccess(name, params) {
      if (['ActivityEditDialog'].includes(name)) {
        this.getData();
      }
      if (['FormDesignerDialog'].includes(name)) {
        this.saveFormOption(params);
      }
    },
    // 保存表单设计选项
    saveFormOption(params) {
      if (this.dialogParams.optionId) {
        api
          .editActivityOption({ id: this.dialogParams.optionId, activityId: this.dialogParams.activityId, ...params })
          .then((res) => {
            this.$message.success({ message: res.msg });
          });
      } else {
        api.addActivityOption({ activityId: this.dialogParams.activityId, ...params }).then((res) => {
          this.$message.success({ message: res.msg });
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';
@include table-page-style;
</style>
